package com.webserver.controller;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.core.DispatcherServlet;
import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理与用户相关的操作
 */
@Controller
public class UserController {
    private static File userDir;

    static {
        userDir = new File("./users");
        if (!(userDir.exists())) {
            userDir.mkdirs();
        }
    }

    @RequestMapping("/myweb/reg")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        //获取用户注册网页上输入的注册信息，获取form表单提交的内容。

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");

        if (username == null || password == null || nickname == null || ageStr == null || !ageStr.matches("[0-9]+")) {
//            File file = new File(staticDir, "/myweb/reg_input_error.html");
//            response.setContentFile(file);
            response.sendRedirect("/myweb/reg_input_error.html");
            return;
        }

        int age = Integer.parseInt(ageStr);
        System.out.println(username + "," + password + "," + nickname + "," + age);

        File userFile = new File(userDir, username + ".obj");
        if (userFile.exists()) {
//            File file = new File(staticDir, "/myweb/have_user.html");
//            response.setContentFile(file);
            response.sendRedirect("/myweb/have_user.html");
            return;
        }
        try (
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos)
        ) {
            User user = new User(username, password, nickname, age);
            oos.writeObject(user);

//            File file = new File(staticDir, "/myweb/reg_success.html");
//            response.setContentFile(file);
            response.sendRedirect("/myweb/reg_success.html");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/myweb/login")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        File file;
        if (username == null || password == null) {
//            file = new File(staticDir, "/myweb/login_info_error.html");
//            response.setContentFile(file);
            response.sendRedirect("/myweb/login_info_error.html");
            return;
        }
        User user = new User();
        file = new File(userDir, username + ".obj");
        if (file.exists()) {
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                user = (User) ois.readObject();
                if (user.getPassword().equals(password)) {
//                    file = new File(staticDir, "/myweb/login_success.html");
//                    response.setContentFile(file);
                    response.sendRedirect( "/myweb/login_success.html");
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
//        file = new File(staticDir, "/myweb/login_fail.html");
//        response.setContentFile(file);
        response.sendRedirect("staticDir, /myweb/login_fail.html");


    }

    @RequestMapping("/myweb/showAllUser")
    public void shouAllUser(HttpServletRequest request, HttpServletResponse response) {
        List<User> userList = new ArrayList<>();
        File[] userFiles = userDir.listFiles(f -> f.getName().endsWith(".obj"));
//        String username ="";
        List<String> time = new ArrayList<>();
        for (File userFile : userFiles) {
            try (
                    FileInputStream fos = new FileInputStream(userFile);
                    ObjectInputStream ois = new ObjectInputStream(fos);
            ) {
                userList.add((User) ois.readObject());
                time.add(fileTime(userFile.getName()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }


        PrintWriter pw = response.getWriter();

        pw.println("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>用户列表</title>\n" +
                "</head>\n" +
                "<center>\n" +
                "    <h1>用户列表</h1>" +
                "<table border=\"1\">\n");
        pw.println(
                "        <tr>\n" +
                        "            <td align=\"center\">用户名</td>\n" +
                        "            <td align=\"center\">密码</td>\n" +
                        "            <td align=\"center\">昵称</td>\n" +
                        "            <td align=\"center\">年龄</td>\n" +
//                        "            <td align=\"center\">发布时间</td>\n" +
                        "        </tr>");
//        int i = 0;
        for (User user : userList) {
            pw.println(
                    "       <tr>\n" +
                            "            <td align=\"center\">" + user.getUsername() + "</td>\n" +
                            "            <td align=\"center\">" + user.getPassword() + "</td>\n" +
                            "            <td align=\"center\">" + user.getNickname() + "</td>\n" +
                            "            <td align=\"center\">" + user.getAge() + "</td>\n" +
                            "            <td align=\"center\"><a href='/myweb/deleteUser?username="+user.getUsername()+"'>删除<a/></td>\n" +
                            "        </tr>\n");
        }

        pw.println("</table>\n" +
                "</center>\n" +
                "\n" +
                "</body>\n" +
                "</html>");

        response.setContentType("text/html");

    }

    public String fileTime(String username) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
        java.nio.file.attribute.FileTime t = null;
        try {
            t = Files.readAttributes(Paths.get(userDir + "/" + username), BasicFileAttributes.class).creationTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String time = dateFormat.format(t.toMillis());
        return time;
    }
    @RequestMapping("/myweb/deleteUser")
    public void deleteUser(HttpServletRequest request, HttpServletResponse response){
        String userName = request.getParameter("username");

        File userFIle = new File(userDir,userName+".obj");
        userFIle.delete();

//        File file = new File(staticDir,"/myweb/deleteUserSuccess.html");
//        response.setContentFile(file);
        response.sendRedirect("/myweb/showAllUser");
    }
}

